package services.dingtalk

import controllers.RequestAsJson
import models.robot.{RobotMassage, RobotMessageRepository, RobotTalk}
import play.api.Logging
import play.api.cache.SyncCacheApi
import services.{LayUIRobotTalk, LayUiRobotMsg}

import java.sql.Timestamp
import java.time.LocalDateTime
import javax.inject.Inject
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}

class RobotMessageService @Inject()(msgRepo: RobotMessageRepository, cache: SyncCacheApi) extends RequestAsJson with Logging {

  def layuiChange(layUIRobotTalk: LayUIRobotTalk): RobotTalk = RobotTalk(
    id = createRobotTalkId(layUIRobotTalk.access.getOrElse("")),
    access = layUIRobotTalk.access.getOrElse(""),
    name = layUIRobotTalk.name.getOrElse(""),
    secret = layUIRobotTalk.secret.getOrElse(""),
    status = if (layUIRobotTalk.status.nonEmpty) true else false,
    note = layUIRobotTalk.note
  )

  def layuiChange(msg: LayUiRobotMsg): RobotMassage = RobotMassage(
    id = createRobotMessageId(msg.msg),
    talkId = getRobotTalkId(msg.talk),
    title = msg.talk,
    msg = msg.msg,
    runtime = if (msg.runtime.isEmpty) Timestamp.valueOf(LocalDateTime.now()) else Timestamp.valueOf(LocalDateTime.parse(msg.runtime)),
    lostTime = if (msg.lostTime.isEmpty) Timestamp.valueOf(LocalDateTime.now()) else Timestamp.valueOf(LocalDateTime.parse(msg.lostTime)),
    sendStatus = msg.sendStatus.toInt
  )

  def layuiChange(x: RobotTalk): LayUIRobotTalk = LayUIRobotTalk(
    id = Some(x.id),
    name = Some(x.name),
    access = Some(x.access),
    secret = Some(x.secret),
    status = if (x.status) Some("是") else Some("否"),
    note = x.note
  )

  def layuiChange(x: RobotMassage): LayUiRobotMsg = LayUiRobotMsg(
    id = x.id,
    talk = getRobotTalkId(x.talkId),
    title = x.title,
    msg = x.msg,
    runtime = x.runtime.toString,
    lostTime = x.lostTime.toString,
    sendStatus = x.sendStatus match {
      case 0 => ""
      case 1 => ""
      case _ => ""
    }
  )


  val hash = security.Encode

  private def createRobotTalkId(access: String) = {
    val time = System.currentTimeMillis() - 1_636_253_224_393L
    val num = access.hashCode & Int.MaxValue
    (time << 32) + num
  }

  private def createRobotMessageId(msg: String) = {
    val time = System.currentTimeMillis() - 1636253224393L
    val num = hash.murmurHash32(msg).asInt() & Int.MaxValue
    (time >>> 6 << 32) + num
  }

  def getRobotTalkId(name: String) = {
    val res = talkIdName.filter(f => f._2 == name)
    if (res.nonEmpty) res.head._1 else 0
  }

  def getRobotTalkId(id: Long) = {
    val res = talkIdName.filter(f => f._1 == id)
    if (res.nonEmpty) res.head._2 else id.toString
  }

  def robotWebApi(queryString: Map[String, Seq[String]], bodyData: AnyVal) = {
    val access = queryString.get("access")
    val hash = queryString.get("hash")
    val sign = queryString.get("sign")
    val timestamp = queryString.get("timestamp")

    Future("")

  }

  def talkIdName = {
    cache.getOrElseUpdate[Seq[(Long, String)]]("dingtalk.robotTalk") {
      Await.result(msgRepo.talkFindAll(), Duration.Inf)
    }
  }

  def talkList(talk: LayUIRobotTalk) = {
    logger.debug(s"talkList is ${talk.toString}")
    msgRepo.talkAllList(talk = layuiChange(talk), page = talk.page, limit = talk.limit)
  }

  def talkAdd(talk: LayUIRobotTalk) = {

  }

  def talkEdit() = {}

  def talkStop() = {}

  def msgList(talkId: Long, title: String, pDateStr: String = "", pStatus: Int = -1, page: Int = 0, limit: Int = 10) = {
    msgRepo.msgTableAllList(talkId = talkId, title = title, pDateStr = pDateStr, pStatus = pStatus, page = page, limit = limit)
  }

  def msgRemove(idList: Array[Long]) = {
    msgRepo.msgTableDelete(idList)
  }

  def msgCreate(message: LayUiRobotMsg) = {
    msgRepo.msgCreate(layuiChange(message))
  }


}
